
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
// app.use(express.urlencoded({ extended: false }))
app.use(express.urlencoded({ extended: false }))
app.userList = [
  {
    name: '张三',
    age: '20'
  }
]
// app.get('/api/jsonp', (req, res) => {
//   let name = req.query.name
//   let password = req.query.password
//   let callback = req.query.callbackName
//   let data = {
//     name,
//     password,
//     age: 20
//   }
//   let result = JSON.stringify(data)
//   // res.setHeader('content-type','jsonp')
//   res.write(`${callback}(${result})`)
//   res.end()
// })
app.get('/api/jsonp', (req, res) => {
  let name = req.query.name
  let password = req.query.password
  let callbackName = req.query.callbackName
  console.log(password);
  let data = {
    name: name,
    age: '20'
  }
  let dataRes = JSON.stringify(data)
  res.write(`${callbackName}(${dataRes})`)
  res.end()
})
app.get('/api/getuser', (req, res) => {
  let name = req.query.name
  let age = req.query.age
  console.log(name, age);
  let data = {
    name,
    age
  }
  let result = JSON.stringify(data)
  res.write(result)
  res.end()
})

app.get('/api/userlist', (req, res) => {
  // let name = req.query.name
  // let age = req.query.age
  // console.log(name,age);
  // let data = {
  //   name,
  //   age
  // }
  let result = JSON.stringify(app.userList)
  res.write(result)
  res.end()
})


app.post('/api/addUser', (req, res) => {
  let name = req.body.name
  let age = req.body.age
  let data = {
    name,
    age
  }
  console.log(data);
  app.userList.push(data)
  res.write(JSON.stringify({
    msg: '数据插入成功',
    status: 200
  }))
  res.end()
  // console.log(data.name);
})

app.listen(3000, () => {
  console.log('监听了3000端口');
})
